//
//  RecognizeImagesView.swift
//  Chatup
//
//  Created by iron man on 2024/1/15.
//

import SwiftUI


struct RecognizeImagesView: View {
    @Environment(\.presentationMode) var presentationMode
    @State private var imaginationText: String = ""
    @State private var hasFile: Bool = false
    @State private var fileName: String = ""
    @State private var fileUrl: URL?
    @State var showImagePicker:Bool = false
    @State var showActionSheet:Bool = false
    @State var image = UIImage()
    @State var sourceType: UIImagePickerController.SourceType = .camera
    @State var showVIP = false
    @State private var showAlert: Bool = false
    @State var isVip = UserDefaults.standard.bool(forKey: "kWhetherVip")
    @State private var isLoading = false
    @State private var showToast = false
    @State private var error: String = ""
    var body: some View {
        ZStack{
            VStack {
                Spacer().frame(height: 16)
                HStack {
                    Button {
                        if isLoading{return}
                        presentationMode.wrappedValue.dismiss()
                    } label: {
                        Image("nav_close")
                            .resizable()
                            .frame(width: 12, height: 12)
                    }
                    Spacer()
                  
                    if !isVip{
                        Button {
                            showVIP.toggle()
                        } label: {
                            Image("icon_setting_vip_right")
                                .resizable()
                                .frame(width: 77, height: 24)
                        }
                    }

                }.padding(.horizontal, 22)
                    
                Spacer().frame(height: 16)
                    
                Text("📷"+String.i18nText("feature_recognize_images"))
                    .font(.system(size: 28).weight(.bold))
                    .foregroundColor(.white)
                Text(String.i18nText("feature_recognize_images_hint"))
                    .font(.system(size: 16))
                    .foregroundColor(Color(red: 0.51, green: 0.51, blue: 0.51))
                    .frame(width: 316, height: 71, alignment: .topLeading)
                    
                Spacer().frame(height: 26)
                HStack{
                    Spacer().frame(width: 22)
                    Button {
                        if(!hasFile){
                            showActionSheet.toggle()
                        }
                    } label: {
                        if(!hasFile){
                            Image("ic_add_image")
                              .resizable()
                              .frame(width: 30, height: 30)
                              .foregroundColor(.clear)
                              .frame(width: 68, height: 68)
                              .background(Color(red: 0.13, green: 0.13, blue: 0.14))
                              .cornerRadius(10)
                        }else{
                            ZStack(alignment: .topTrailing) {
                                Image(uiImage: image)
                                    .resizable()
                                    .aspectRatio(contentMode: .fill)
                                    .foregroundColor(.clear)
                                    .frame(width: 68, height: 68)
                                    .background(Color(red: 0.13, green: 0.13, blue: 0.14))
                                    .cornerRadius(10)
                                Image("ic_delete")
                                  .resizable()
                                  .aspectRatio(contentMode: .fill)
                                  .frame(width: 27, height: 27)
                                  .clipped()
                                  .onTapGesture {
                                      hasFile = false
                                      fileUrl = nil
                                  }
                            }
                        }
                        
                    }
                    .actionSheet(isPresented: $showActionSheet) {
                                ActionSheet(
                                    title: Text("Recognize Images"),
                                    message: Text("Select from gallery or take a photo"),
                                    buttons: [
                                        .default(Text("Select from Gallery")) {
                                            sourceType = .photoLibrary
                                            showImagePicker = true
                                        },
                                        .default(Text("Take a photo")) {
                                            sourceType = .camera
                                            showImagePicker = true
                                        },
                                        .cancel()
                                    ]
                                )
                            }
                    .sheet(isPresented: $showImagePicker) {
                        ImagePickerView(isPresented: $showImagePicker, selectedImage: $image, hasFile: $hasFile, fileUrl: $fileUrl, sourceType: $sourceType)
                    }

                    Spacer()
                }
                Spacer().frame(height: 20)
                
                    
                TextView(hint: String.i18nText("feature_recognize_images_hint2"), text: $imaginationText).padding(.horizontal,23)
                    
                Spacer()


                Button(action: {
                    isVip = UserDefaults.standard.bool(forKey: "kWhetherVip")
                    if !isVip {
                        showVIP.toggle()
                        return
                    }
                    
                    if !hasFile{
                        return
                    }
                    
                    if isLoading{return}
                    isLoading = true
                    
                    RecognizeImageMessageBuilder().uploadFile(filePath: fileUrl!) { url,code,msg in
                        self.isLoading = false
                        if code == -1{
                            DispatchQueue.main.async {
                                NotificationCenter.default.post(name: Notification.Name("kGpt3OverSizeMessage"), object: nil)
                            }
                            presentationMode.wrappedValue.dismiss()
                            return
                        }else if code == -2 {
                            DispatchQueue.main.async {
                                NotificationCenter.default.post(name: Notification.Name("kGpt4OverSizeMessage"), object: nil)
                            }
                            presentationMode.wrappedValue.dismiss()
                            return
                        }else if url == nil {
                            if msg == nil{
                                presentationMode.wrappedValue.dismiss()
                            }else{
                                self.error = msg!
                                self.showToast.toggle()
                                DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) {
                                    withAnimation {
                                        self.showToast.toggle()
                                    }
                                }
                            }
                            
                            return
                        } else{
                            
                            let imageModel = MsgModel(type: .user,   messageType: .networkImage, message: url!, roleId: 0, isLike: false, isUnlike: false)
                            let msgModel  = MsgModel(type: .user, messageType: .text, message: imaginationText, roleId: 0, isLike: false, isUnlike: false)
                            
                            let msg1Model  = MsgModel(type: .bot, messageType: .text, message:  "", roleId: 0, isLike: false, isUnlike: false, context: url! + "#" + imaginationText)
                            DispatchQueue.main.async {
                                NotificationCenter.default.post(name: Notification.Name("kAppendMessage"), object: ["feature":FeaturesType.recognizeImage,"msgs":[imageModel, msgModel, msg1Model]])
                                
                                presentationMode.wrappedValue.dismiss()
                            }
                        }
                        
                    }
                    
                    
                }) {
                    Text(String.i18nText("feature_recognize"))
                        .font(.system(size: 18).weight(.bold))
                        .foregroundColor(Color(red: 1, green: 1, blue: 1))
                        .foregroundColor(.clear)
                        .frame(minWidth: 0, maxWidth: .infinity)
                        .frame(height: 57)
                        .background(
                            imaginationText.isEmpty ? Color(red: 0.54, green: 0.54, blue: 0.55):
                            Color(red: 0.15, green: 0.75, blue: 0.46)
                        )
                        .cornerRadius(12)
                }
                .padding()

                Spacer().frame(height: 32)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.black.opacity(0.8))
            .edgesIgnoringSafeArea(.all)
            .fullScreenCover(isPresented: $showVIP, content: {
                VipView(viewModel: .init(from: "feature_recognize_images"))
            })
            .onReceive(NotificationCenter.default.publisher(for: Notification.Name("refreshVip"))) { _ in
                isVip = UserDefaults.standard.bool(forKey: "kWhetherVip")
            }
            .onTapGesture {
                NotificationCenter.default.post(name: Notification.Name("kChangeFocused"), object: nil)
            }.alert(isPresented: $showAlert) {
                // 创建Alert实例
                Alert(
                    title: Text(""),
                    message: Text(String.i18nText("chat_no_credit_gpt4.0")),
                    dismissButton: .default(Text(String.i18nText("continue"))) {
                        // 点击好的按钮后的操作
                        
                    }
                )
            }
            
            if isLoading{
                ProgressView()
                    .progressViewStyle(CircularProgressViewStyle(tint: .white))
                    .scaleEffect(2)
            }
            if showToast{
                ToastView(text: error)
            }
        }
    }
}
    

struct ImagePickerView:UIViewControllerRepresentable{
    @Binding var isPresented:Bool
    @Binding var selectedImage:UIImage
    @Binding var hasFile:Bool
    @Binding var fileUrl:URL?
    @Binding var sourceType: UIImagePickerController.SourceType
    func makeCoordinator() -> Coordinator {
        return Coordinator(parent: self)
    }
    
    class Coordinator:NSObject,UINavigationControllerDelegate,UIImagePickerControllerDelegate{
        var parent:ImagePickerView
        init(parent:ImagePickerView) {
            self.parent = parent
        }
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            if let selectedImage = info[.originalImage] as? UIImage{
                let url = info[.imageURL] as? URL
                self.parent.selectedImage = selectedImage
                self.parent.hasFile = true
                self.parent.isPresented = false
                
                if url == nil{
                    let data = selectedImage.jpegData(compressionQuality: 0.5)
                    let fileManager: FileManager = FileManager.default
                    if let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
                        let filePath = documentDirectory.appendingPathComponent("image.png")
                        do {
                            try data?.write(to: filePath, options: .atomic)
                            self.parent.fileUrl = filePath
                        } catch let error {
                            print("Error saving file: \(error)")
                        }
                    }
                    
                }else{
                    self.parent.fileUrl = url
                }
                
            }
        }
    }
    
    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
        
    }
    
    func makeUIViewController(context: Context) -> some UIViewController {
        let controller = UIImagePickerController()
        controller.allowsEditing = true
        controller.sourceType = sourceType
        controller.delegate = context.coordinator
        return controller
    }
}


